package com.ctim.service.user;

import com.ctim.common.exception.EnumPcsService;
import com.ctim.common.exception.PcsRunTimeException;
import com.ctim.dao.user.ResourceDao;
import com.ctim.model.user.Resource;
import com.ctim.model.user.User;
import com.ctim.service.enums.ResourceType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Author: Wangwei
 * Date: 2016/9/9
 * Desc:资源Service
 */
@Service
public class ResourceService {

    @Autowired
    private ResourceDao resourceDao;

    /**
     * 获取用户所有 资源
     * @param userId
     * @return  key: permissions, menuTree
     */
    public Map<String, List<Resource>> getUserResources(Integer userId) {
        Map<String, List<Resource>> map = new HashMap<>();
        List<Resource> permissions = new ArrayList<>();
        List<Resource> menu = new ArrayList<>();
        List<Resource> allResource = resourceDao.getUserResources(userId);
        for (int i=0; i<allResource.size(); i++) {
            Resource resource = allResource.get(i);
            if (resource.getType().equals(ResourceType.PERMISSION.getValue())) {
                permissions.add(resource);
            } else {
                menu.add(resource);
            }
        }
        List<Resource> menuTree = buildResource(menu);
        map.put("permissions", permissions);
        map.put("menuTree", menuTree);
        return map;
    }


    /**
     * 获取所有资源 tree
     * @return
     */
    public List<Resource> getResources() {
        return buildResource(resourceDao.getResources(null));
    }

    /**
     * 获取权限 列表
     * @return list
     */
    public List<Resource> getPermission(Integer parentId) {
        List<Resource> list = new ArrayList<>();
        return buildPermission(list, parentId);
    }


    /**
     * 获取 菜单树
     * @return
     */
    public List<Resource> getMenuTree() {
        return buildResource(resourceDao.getMenus());
    }

    /**
     * 新增 资源
     * @param resource
     * @return
     */
    public boolean insertResource(Resource resource,User user) {
        if (resourceDao.selectResource(resource)!=null) {
            throw new PcsRunTimeException(EnumPcsService.BUSINESS_RESOURCE_EXISTED);
        }
        resource.setCreateUid(user.getUserId());
        return resourceDao.insertResource(resource)>0;
    }

    /**
     * 修改资源
     * @param resource
     * @return
     */
    public boolean updateResource(Resource resource,User user){
        Resource r = resourceDao.selectResource(resource);
        if (r!=null && r.getId().intValue()!=resource.getId().intValue()) {
            throw new PcsRunTimeException(EnumPcsService.BUSINESS_RESOURCE_EXISTED);
        }
        resource.setUpdateUid(user.getUserId());
        return resourceDao.updateResource(resource)>0;
    }

    /**
     * 删除 资源  如果有子资源 则一起删除
     * @param resourceId
     * @return
     */
    public boolean deleteResource(Integer resourceId){
        return resourceDao.deleteResource(resourceId)>0;
    }

    /**
     * 切换 资源 状态  0：无效，1：有效
     * @param resourceId
     * @param status
     * @return
     */
    public boolean toggleEnable(Integer resourceId, Integer userId, Integer status) {
        return resourceDao.toggleEnable(resourceId, status, userId)>0;
    }

    /*************************   private methods       *****************************/

    /**
     * 构建 权限列表      递归查询父id下面所有权限
     * @param list
     * @param parentId
     * @return
     */
    private List<Resource> buildPermission(List<Resource> list, Integer parentId) {
        List<Resource> resources = resourceDao.getResources(parentId);
        for (Resource resource: resources) {
            if (resource.getParentId()>0 && resource.getType().equals(ResourceType.PERMISSION.getValue())) {
                list.add(resource);
            } else {
                buildPermission(list, resource.getId());
            }
        }
        return list;
    }

    /**
     * 构建 资源树       @1
     * @param list list
     * @return list
     */
    public List<Resource> buildResource(List<Resource> list) {
        List<Resource> target = new ArrayList<>();
        if (!list.isEmpty()) {
            // 根元素
            list.stream().filter(resource -> resource.getParentId().intValue() == 0).forEach(resource -> {// 根元素
                List<Resource> children = getChildren(resource, list);
                resource.setChildren(children);
                target.add(resource);
            });
        }
        return target;
    }

    /**
     * 构建 资源树       @2
     * @param resource
     * @param list
     * @return
     */
    private List<Resource> getChildren(Resource resource, List<Resource> list) {
        List<Resource> children = new ArrayList<>();
        if (!list.isEmpty()) {
            for (Resource child: list) {
                if (resource.getId().intValue() == child.getParentId().intValue()) {
                    List<Resource> tmp = getChildren(child, list);
                    child.setChildren(tmp);
                    if (tmp.isEmpty()) {
                        child.setLeaf(true);
                    }
                    children.add(child);
                }
            }
        }
        return children;
    }



}
